import { fabric } from "fabric";
import { jsPDF } from "jspdf";
class TagGraph {
  constructor(canvasId, initData, callback) {
    fabric.devicePixelRatio = 2;
    this.canvas = new fabric.Canvas(canvasId, {
      preserveObjectStacking: true
    });
    this.stateStack = [];
    this.redoStack = [];
    this.customProperties = [
      "componentType",
      "borderColor",
      "cornerColor",
      "cornerSize",
      "transparentCorners",
      "editingBorderColor",
      "width",
      "height",
      "hasControls",
      "textType",
      "textPrefix",
      "textSuffix",
      "qrcodeType",
      "lineType",
      "dynamicTextContent",
      "dynamicTextIncrement",
      "dynamicTextNumber",
      "barcodeType",
      "barcodeTextPosition",
      "text",
      "uniformScaling",
      "fixedWidth",
      "componentType",
      "padding",
      "displayText",
      "lastedUpdateTimestamp",
      "inheritTextEditor",
      "fontFamily",
      "fontSize",
      "objectCaching",
      "noScaleCache",
      "relationExcelId",
      "relationExcelColumnId",
      "_id",
      "_comp",
      "errorLevel",
      "lockScalingX",
      "lockScalingY",
      "lockMovementX",
      "lockMovementY",
      "lockRotation",
      "hoverCursor",
      "dateValue",
      "dateFormat",
      "timeFormat",
      "yearOffset",
      "monthOffset",
      "dayOffset",
      "hourOffset"
    ];
    this.activeObject = null;
    this.initializeCanvas(initData, callback);
  }

  // 初始化画布
  initializeCanvas(initData, callback) {
    const { width, height, objects, viewportTransform } = initData;

    this.canvas.setWidth(width);
    this.canvas.setHeight(height);
    this.canvas.renderOnAddRemove = true;
    this.canvas.backgroundColor = "#ffffff";
    this.canvas.viewportTransform = viewportTransform || [0, 0, 0, 0, 0, 0];

    if (objects) this.loadFromJSON(initData, callback);
    else callback();
    // if (backgroundImage && Object.keys(backgroundImage).length)
    // this.setBackgroundImage(backgroundImage);
  }

  // 保存当前画布状态
  saveState() {
    const json = this.canvas.toJSON(this.customProperties);
    this.redoStack = [];
    this.stateStack.push(json);
  }
  // 获取当前选中的对象
  getActiveObject = () => this.canvas.getActiveObject();

  // 获取当前选中的对象
  getActiveObjects = () => this.canvas.getActiveObjects();

  // 设置画布背景颜色
  setBackgroundColor = color => this.canvas.setBackgroundColor(color);

  // 设置画布背景图片
  setBackgroundImage = img => {
    this.canvas.setBackgroundImage(img);
  };

  // 获取image实例
  getImage = base64 => {
    console.log(this.canvas.getZoom());

    return new Promise(resolve => {
      fabric.Image.fromURL(base64, img => {
        img.set({
          componentType: "image",
          left: 0,
          top: 0,
          // scaleX: img.width / this.canvas.getWidth(),
          // scaleY: img.height / this.canvas.getHeight(),
          originX: "left",
          originY: "top"
        });
        img.zoom = this.canvas.getZoom();
        img.viewportTransform = this.canvas.viewportTransform;

        resolve(img);
        return img;
      });
    });
  };

  // 获取当前画布的宽度
  getWidth = () => this.canvas.getWidth();

  // 获取当前画布的高度
  getHeight = () => this.canvas.getHeight();

  // 设置画布的宽度
  setCancasWidth = width => this.canvas.setWidth(width);

  // 设置画布的高度
  setCancasHeight = height => this.canvas.setHeight(height);

  // 从画布中移除指定的图形对象
  remove = obj => this.canvas.remove(obj);

  // 清空画布
  clear = () => this.canvas.clear();

  // 保存画布Json数据
  save = () => this.canvas.toJSON(this.customProperties);

  // 添加矩形
  addRectangle(options) {
    const rect = new fabric.Rect({
      componentType: "rect",
      left: 100,
      top: 100,
      shape: "rect",
      strokeUniform: true,
      fill: "transparent",
      strokeWidth: 2.25,
      stroke: "black",
      borderColor: "#FF8602",
      cornerColor: "#FF8602",
      fillRule: "nonzero",
      transparentCorners: false,
      editingBorderColor: "#FF8602",
      cornerSize: 12,
      width: 50,
      height: 50,
      angle: 0,
      ...options
    });
    this.add(rect);
    this.canvas.setActiveObject(rect);
    return rect;
  }

  // 添加圆形
  addEllipse(options) {
    const ellipse = new fabric.Ellipse({
      componentType: "ellipse",
      left: 100,
      top: 100,
      fill: "transparent",
      originX: "left",
      originY: "top",
      rx: 25,
      ry: 25,
      strokeUniform: true,
      fillRule: "nonzero",
      strokeRxRy: 20,
      objectCaching: true,
      globalCompositeOperation: "source-over",
      noScaleCache: true,
      paintFirst: "fill",
      stroke: "black",
      strokeWidth: 2.25,
      shape: "ellipse",
      borderColor: "#FF8602",
      cornerColor: "#FF8602",
      transparentCorners: false,
      editingBorderColor: "#FF8602",
      cornerSize: 12,
      strokeWidth: 2.25,
      ...options
    });
    this.add(ellipse);
    this.canvas.setActiveObject(ellipse);
    return ellipse;
  }

  // 添加文本
  addIText(text, options) {
    const textObj = new fabric.Textbox(text, {
      type: "textbox",
      left: 50,
      top: 50,
      width: 150,
      height: 50,
      originX: "left",
      originY: "top",
      fill: "rgb(0,0,0)",
      borderColor: "#FF8602",
      cornerColor: "#FF8602",
      lineHeight: 1,
      uniformScaling: false,
      hasControls: true,
      fontFamily: "Microsoft Yahei",
      componentType: "text",
      editingBorderColor: "#FF8602",
      transparentCorners: false,
      textBackgroundColor: "rgba(0,0,0,0)",
      fontSize: 15.874,
      cornerColor: "#FF8602",
      cornerSize: 12,
      charSpacing: 1,
      textType: "manual",
      dynamicTextContent: "",
      dynamicTextIncrement: 1,
      dynamicTextNumber: 1,
      barcodeType: "",
      barcodeTextPosition: "",
      ...options
    });

    this.add(textObj);
    this.canvas.setActiveObject(textObj);
    return textObj;
  }

  // 添加日期
  addText(text, options) {
    const textObj = new fabric.Textbox(text, {
      left: 100,
      top: 100,
      width: 120,
      height: 50,
      originX: "left",
      originY: "top",
      fill: "rgb(0,0,0)",
      borderColor: "#FF8602",
      cornerColor: "#FF8602",
      componentType: "date",
      editingBorderColor: "#FF8602",
      transparentCorners: false,
      textBackgroundColor: "rgba(0,0,0,0)",
      cornerColor: "#FF8602",
      barcodeType: "",
      uniformScaling: false,
      editable: false,
      hasControls: true,
      barcodeTextPosition: "",
      padding: 0,
      fontSize: 15.874,
      fontFamily: "Microsoft Yahei",
      objectCaching: true,
      noScaleCache: true,
      relationExcelId: "",
      relationExcelColumnId: "",
      hoverCursor: null,
      ...options
    });
    this.add(textObj);
    this.canvas.setActiveObject(textObj);
    return textObj;
  }
  // 添加二维码
  addqrCodeImage(base64, options) {
    return new Promise((resolve, reject) => {
      fabric.Image.fromURL(
        base64,
        img => {
          img.set({
            left: 100,
            fill: "rgb(0,0,0)",
            backgroundColor: "rgba(0,0,0,0)",
            visible: true,
            stroke: null,
            strokeWidth: 0,
            strokeDashArray: null,
            strokeLineCap: "butt",
            strokeDashOffset: 0,
            strokeLineJoin: "miter",
            borderColor: "#FF8602",
            cornerColor: "#FF8602",
            componentType: "qrcode",
            editingBorderColor: "#FF8602",
            transparentCorners: false,
            textBackgroundColor: "#ffffff",
            strokeMiterLimit: 4,
            opacity: 1,

            shadow: null,
            fillRule: "nonzero",
            paintFirst: "fill",
            globalCompositeOperation: "source-over",
            transformMatrix: null,
            top: 50,
            scaleX: 0.1,
            scaleY: 0.1,
            ...options
          });
          this.add(img);
          this.canvas.setActiveObject(img);
          resolve(img);
        },
        reject
      );
    });
  }
  // 添加条形码
  addbarCodeImage(base64, options) {
    return new Promise((resolve, reject) => {
      fabric.Image.fromURL(
        base64,
        img => {
          img.set({
            top: 50,
            left: 50,
            fill: "rgb(0,0,0)",
            backgroundColor: "rgba(0,0,0,0)",
            visible: true,
            stroke: null,
            hasControls: true,
            strokeWidth: 0,
            strokeDashArray: null,
            strokeLineCap: "butt",
            strokeDashOffset: 0,
            hasControls: true,
            fontFamily: "SimHei",
            strokeLineJoin: "miter",
            borderColor: "#FF8602",
            cornerColor: "#FF8602",
            componentType: "barcode",
            editingBorderColor: "#FF8602",
            transparentCorners: false,
            textBackgroundColor: "#ffffff",
            strokeMiterLimit: 4,
            opacity: 1,
            shadow: null,
            fillRule: "nonzero",
            paintFirst: "fill",
            globalCompositeOperation: "source-over",
            transformMatrix: null,
            scaleX: 0.1,
            scaleY: 0.1,
            ...options
          });
          this.canvas.setActiveObject(img);
          this.add(img);
          resolve(img);
        },
        reject
      );
    });
  }

  // 添加base64图片
  addBase64Image(base64, options) {
    fabric.Image.fromURL(base64, img => {
      img.set({
        componentType: "image",
        left: 100,
        top: 100,
        borderColor: "#FF8602",
        cornerColor: "#FF8602",
        editingBorderColor: "#FF8602",
        transparentCorners: false,
        scaleX: 0.2,
        scaleY: 0.2,
        ...options
      });
      this.add(img);
    });
  }
  // 添加线条
  addLine(options) {
    const line = new fabric.Line([10, 10, 200, 10], {
      //线条类型
      componentType: "line",
      padding: 10,
      left: 100,
      top: 100,
      originX: "left",
      originY: "top",
      stroke: "black",
      strokeWidth: 2.25,
      strokeDashArray: [],
      strokeLineCapL: "round",
      borderColor: "#FF8602",
      strokeMiterLimit: 4,
      cornerSize: 12,
      globalCompositeOperation: "source-over",
      cornerColor: "#FF8602",
      cornerSize: 12,
      transparentCorners: false,
      ...options
    });
    this.add(line);
    this.canvas.setActiveObject(line);
    return line;
  }

  // 清除画布
  clearCanvas = () => this.canvas.clear();

  // 全选组件
  selectAll() {
    this.canvas.discardActiveObject();
    const sel = new fabric.ActiveSelection(this.canvas.getObjects(), {
      canvas: this.canvas
    });
    this.canvas.setActiveObject(sel);
    this.canvas.requestRenderAll();
  }

  // 删除选中的对象
  deleteSelected() {
    const activeObjects = this.canvas.getActiveObjects();
    console.log(activeObjects);

    if (activeObjects.length) {
      activeObjects.forEach(object => {
        this.canvas.remove(object);
      });
      this.saveState();
      this.canvas.discardActiveObject().renderAll(); // 清除选中状态并重新渲染画布
    }
  }

  // 复制选中的对象
  copySelected() {
    const activeObject = this.canvas.getActiveObject();

    if (activeObject) {
      activeObject.clone(cloned => {
        this.clipboard = cloned;
        this.paste();
      }, this.customProperties);
    }
  }

  // 粘贴复制的对象
  paste() {
    if (this.clipboard) {
      this.clipboard.clone(clonedObj => {
        this.canvas.discardActiveObject();
        clonedObj.set({
          left: clonedObj.left + 10,
          top: clonedObj.top + 10,
          evented: true
        });
        if (clonedObj.type === "activeSelection") {
          clonedObj.canvas = this.canvas;
          clonedObj.forEachObject(obj => {
            this.add(obj);
          });
          clonedObj.setCoords();
        } else {
          this.add(clonedObj);
        }
        this.clipboard.top += 10;
        this.clipboard.left += 10;
        this.canvas.setActiveObject(clonedObj);
        this.canvas.requestRenderAll();
      }, this.customProperties);
    }
  }
  // 提高选中对象的图层等级

  /**
   * @description 改变选中对象的图层等级
   * @param  bringForward 向前移动一层
   * @param sendBackward 向后移动一层
   * @param bringToFront 移动到最顶层
   * @param sendToBack 移动到最底层
   */
  changeLayer(action) {
    const activeObject = this.canvas.getActiveObject();
    if (activeObject) {
      switch (action) {
        case "bringForward":
          this.canvas.bringForward(activeObject);
          break;
        case "sendBackward":
          this.canvas.sendBackwards(activeObject, true);
          break;
        case "bringToFront":
          this.canvas.bringToFront(activeObject);
          break;
        case "sendToBack":
          this.canvas.sendToBack(activeObject);
          break;
        default:
          console.error("未知的图层操作:", action);
      }
      console.log("activeObject :>> ", activeObject);
      this.canvas.renderAll();
      this.saveState();
    }
  }

  // 添加元素
  add(obj) {
    this.canvas.add(obj);
    this.saveState();
  }
  // 撤销操作
  undo() {
    console.log(this.stateStack);

    if (this.stateStack.length > 1) {
      const currentState = this.stateStack[this.stateStack.length - 1];
      const previousState = this.stateStack[this.stateStack.length - 2];
      const stateNum = this.stateStack.length;
      this.redoStack.push(currentState);
      this.canvas.loadFromJSON(previousState, () => {
        this.stateStack = this.stateStack.slice(0, stateNum - 1);
      });
    }
  }

  // 恢复操作
  redo() {
    if (this.redoStack.length > 0) {
      const nextState = this.redoStack.pop();
      this.stateStack.push(nextState);
      const stateNum = this.stateStack.length;
      this.canvas.loadFromJSON(nextState, () => {
        this.stateStack = this.stateStack.slice(0, stateNum);
      });
    }
  }

  // 旋转选中的对象
  rotateSelected() {
    const activeObject = this.canvas.getActiveObject();
    if (activeObject) {
      const currentAngle = activeObject.angle || 0;
      activeObject.rotate(currentAngle + 90);
      this.canvas.renderAll();
      this.saveState();
    }
  }

  // 解析数据并添加到画布
  loadFromJSON(json, callback) {
    this.canvas.loadFromJSON(json, () => {
      this.saveState();
      callback && callback();
    });
    return this.canvas;
  }
  // 设置画布背景为白色并导出为图片
  exportCanvasAsImage(format, filename) {
    console.log(format);

    // 保存当前背景颜色
    const originalBackgroundColor = this.canvas.backgroundColor;

    // 设置背景颜色为白色
    this.canvas.backgroundColor = "#ffffff";

    // 渲染画布
    this.canvas.renderAll();

    // 导出画布为图片
    const dataURL = this.canvas.toDataURL({
      format: format,
      quality: 1.0,
      multiplier: 1.0,
      enableRetinaScaling: true,
      withoutTransform: true,
      withoutShadow: true
    });

    // 创建下载链接
    const link = document.createElement("a");
    link.href = dataURL;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 恢复原始背景颜色
    this.canvas.backgroundColor = originalBackgroundColor;
    this.canvas.renderAll();
  }

  // 导出画布为PNG图片并立即下载
  exportAsPNG(name) {
    this.exportCanvasAsImage("png", name);
  }

  // 导出画布为JPG图片并立即下载
  exportAsJPG(name) {
    this.exportCanvasAsImage("jpeg", name);
  }
  // 导出画布为JPG图片并立即下载
  exportAsPDF(name) {
    this.exportCanvasAsPDF(name);
  }

  // 导出画布为PDF文件并立即下载
  exportCanvasAsPDF(name) {
    const originalBackgroundColor = this.canvas.backgroundColor;
    this.canvas.backgroundColor = "#ffffff";
    this.canvas.renderAll();

    const dataURL = this.canvas.toDataURL({
      format: "jpeg",
      quality: 1.0,
      multiplier: 1.0,
      enableRetinaScaling: true,
      withoutTransform: true,
      withoutShadow: true
    });

    const pdf = new jsPDF("landscape", "pt", [
      this.canvas.width,
      this.canvas.height
    ]);
    pdf.addImage(dataURL, "JPEG", 0, 0, this.canvas.width, this.canvas.height);
    pdf.save(name);

    this.canvas.backgroundColor = originalBackgroundColor;
    this.canvas.renderAll();
  }
  // 预览画布
  preview() {
    return this.canvas.toDataURL({ format: "png", quality: 1.0 });
  }
  /**
* @description 对齐选中的对象
* @param alignment 对齐方式
* @param left 左对齐
* @param right 右对齐
* @param top 上对齐
* @param bottom 下对齐
* @param center 水平居中对齐
* @param middle 垂直居中对齐
 
*/
  alignSelected(alignment) {
    const activeObject = this.canvas.getActiveObject();
    if (activeObject && activeObject.type === "activeSelection") {
      activeObject.forEachObject(obj => {
        const objWidth = obj.getScaledWidth();
        const objHeight = obj.getScaledHeight();

        switch (alignment) {
          case "left":
            obj.set({ left: -activeObject.width / 2 });
            break;
          case "right":
            obj.set({ left: activeObject.width / 2 - objWidth });
            break;
          case "top":
            obj.set({ top: -activeObject.height / 2 });
            break;
          case "bottom":
            obj.set({ top: activeObject.height / 2 - objHeight });
            break;
          case "center": // 水平居中
            obj.set({ left: -objWidth / 2 });
            break;
          case "middle": // 垂直居中
            obj.set({ top: -objHeight / 2 });
          default:
            console.warn(`Unknown alignment: ${alignment}`);
        }
        obj.setCoords();
      });
      this.canvas.requestRenderAll();
    }
    this.saveState();
  }

  // 获取画布对象
  getCanvas = () => this.canvas;
  // 设置文本加粗
  setBold() {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("fontWeight", obj.fontWeight === "bold" ? "normal" : "bold");
      });
    } else if (
      activeObject &&
      ["text", "date"].includes(activeObject.componentType)
    ) {
      this.setCustomProperties(
        "fontWeight",
        activeObject.fontWeight === "bold" ? "normal" : "bold"
      );
    }
    this.canvas.renderAll();
    this.saveState();
  }

  // 设置文本斜体
  setItalic() {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("fontStyle", obj.fontStyle === "italic" ? "normal" : "italic");
      });
    } else if (
      activeObject &&
      ["text", "date"].includes(activeObject.componentType)
    ) {
      this.setCustomProperties(
        "fontStyle",
        activeObject.fontStyle === "italic" ? "normal" : "italic"
      );
    }
    this.canvas.renderAll();
    this.saveState();
  }

  // 设置文本下划线
  setUnderline() {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("underline", !obj.underline);
      });
    } else if (
      activeObject &&
      ["text", "date"].includes(activeObject.componentType)
    ) {
      this.setCustomProperties("underline", !activeObject.underline);
    }
    this.canvas.renderAll();
    this.saveState();
  }
  // 设置文本删除线
  setLinethrough() {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("linethrough", !obj.linethrough);
      });
    } else if (
      activeObject &&
      ["text", "date"].includes(activeObject.componentType)
    ) {
      this.setCustomProperties("linethrough", !activeObject.linethrough);
    }
    this.canvas.renderAll();
    this.saveState();
  }
  // 设置文本对齐方式
  setTextAlign(align) {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("textAlign", align);
      });
    } else if (
      activeObject &&
      ["text", "date"].includes(activeObject.componentType)
    ) {
      this.setCustomProperties("textAlign", align);
    }
    this.canvas.renderAll();
    this.saveState();
  }
  //设置文本镜像
  setFlip() {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("flipX", !obj.flipX);
      });
    } else if (activeObject) {
      this.setCustomProperties("flipX", !activeObject.flipX);
    }
    this.canvas.renderAll();
    this.saveState();
  }
  //设置文本颜色为白色 背景为黑色 再次点击取反
  setTextColor() {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        if (obj.fill === "#000") {
          obj.set("fill", "#fff");
          obj.set("textBackgroundColor", "black");
        } else {
          obj.set("fill", "#000");
          obj.set("textBackgroundColor", "white");
        }
      });
    } else if (
      activeObject &&
      ["text", "date"].includes(activeObject.componentType)
    ) {
      if (activeObject.fill === "#000") {
        this.setCustomProperties("fill", "#fff");
        this.setCustomProperties("textBackgroundColor", "black");
      } else {
        this.setCustomProperties("fill", "#000");
        this.setCustomProperties("textBackgroundColor", "white");
      }
    }
    this.canvas.renderAll();
    this.saveState();
  }
  // 设置文本字体
  setFontFamily(fontFamily) {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("fontFamily", fontFamily);
      });
    } else if (
      activeObject &&
      (activeObject.type === "textbox" ||
        activeObject.componentType === "date" ||
        activeObject.componentType === "barcode")
    ) {
      this.setCustomProperties("fontFamily", fontFamily);
    }
    this.canvas.renderAll();
    this.saveState();
  }

  // 设置文本字号
  setFontSize(fontSize) {
    const activeObject = this.canvas.getActiveObject();

    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("fontSize", fontSize);
      });
    } else if (
      activeObject.type === "textbox" ||
      activeObject.componentType === "date" ||
      activeObject.componentType === "barcode"
    ) {
      this.setCustomProperties("fontSize", fontSize * 1.764);
    }

    this.canvas.renderAll();
    this.saveState();
  }

  // 设置文本字间距
  setCharSpacing(charSpacing) {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("charSpacing", charSpacing * 10);
      });
    } else if (activeObject && activeObject.type === "textbox") {
      this.setCustomProperties("charSpacing", charSpacing * 10); // Fabric.js 中的 charSpacing 以 1/1000 em 为单位
    }
    this.canvas.renderAll();
    this.saveState();
  }

  // 设置文本行间距
  setLineHeight(lineHeight) {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;

    if (activeObject._objects) {
      activeObject._objects.forEach(obj => {
        obj.set("lineHeight", lineHeight);
      });
    } else if (activeObject && activeObject.type === "textbox") {
      this.setCustomProperties("lineHeight", lineHeight);
    }
    this.canvas.renderAll();
    this.saveState();
  }
  //设置选中对象的x坐标
  setX(x) {
    const activeObject = this.canvas.getActiveObject();
    console.log(activeObject);

    if (activeObject) {
      this.setCustomProperties("left", x * 1);
      console.log(activeObject);
      this.canvas.renderAll();
      this.saveState();
    }
  }
  //设置选中对象的y坐标
  setY(y) {
    const activeObject = this.canvas.getActiveObject();
    if (activeObject) {
      this.setCustomProperties("top", y * 1);
      this.canvas.renderAll();
      this.saveState();
    }
  }
  //设置选中对象的宽度
  setWidth(width) {
    const activeObject = this.canvas.getActiveObject();
    console.log(activeObject);

    if (activeObject) {
      this.setCustomProperties("width", width * 1);
      this.canvas.renderAll();
      this.saveState();
    }
  }
  //设置选中对象的高度
  setHeight(height) {
    const activeObject = this.canvas.getActiveObject();
    if (activeObject) {
      this.setCustomProperties("height", height * 1);
      this.canvas.renderAll();
      this.saveState();
    }
  }

  //设置选中对象的src
  setSrc(src) {
    const activeObject = this.canvas.getActiveObject();

    if (activeObject && activeObject.type === "image") {
      // 判断 src 是否存在
      if (activeObject.getSrc()) {
        // 清空 src
        activeObject.setSrc("");
        this.canvas.renderAll();
      }

      // 设置新的 src
      fabric.Image.fromURL(src, img => {
        activeObject.setElement(img.getElement());
        this.canvas.renderAll();
      });
    }
  }

  // 设置自定义属性
  setCustomProperties(name, value) {
    let set = new Set(this.customProperties);
    set.add(name);
    this.customProperties = Array.from(set);
    const activeObject = this.canvas.getActiveObject();
    activeObject.set(name, value);
  }
  // 设置缩放
  setZoom(zoom) {
    setTimeout(() => {
      let canvas = this.canvas;
      canvas.setZoom(zoom);
      canvas.renderAll();
    }, 0);
  }

  // 添加表格
  addTable(rows, cols, cellWidth, cellHeight, options = {}) {
    const tableGroup = new fabric.Group([], {
      left: 100,
      top: 100,
      ...options
    });

    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const rect = new fabric.Rect({
          left: col * cellWidth,
          top: row * cellHeight,
          width: cellWidth,
          height: cellHeight,
          fill: "white",
          stroke: "black",
          strokeWidth: 1,
          selectable: false
        });

        const text = new fabric.IText("", {
          left: col * cellWidth + cellWidth / 2,
          top: row * cellHeight + cellHeight / 2,
          fontSize: 12,
          originX: "center",
          originY: "center",
          editable: true,
          selectable: true
        });

        const cellGroup = new fabric.Group([rect, text], {
          left: col * cellWidth,
          top: row * cellHeight,
          selectable: true,
          hasControls: false,
          hasBorders: false
        });

        tableGroup.addWithUpdate(cellGroup);
      }
    }

    this.canvas.add(tableGroup);
    this.canvas.setActiveObject(tableGroup);
    this.saveState();
    return tableGroup;
  }

  // 合并单元格
  mergeCells(tableGroup, startRow, startCol, endRow, endCol) {
    const cells = tableGroup.getObjects();
    const cellWidth = cells[0].width;
    const cellHeight = cells[0].height;

    const mergedRect = new fabric.Rect({
      left: startCol * cellWidth,
      top: startRow * cellHeight,
      width: (endCol - startCol + 1) * cellWidth,
      height: (endRow - startRow + 1) * cellHeight,
      fill: "white",
      stroke: "black",
      strokeWidth: 1,
      selectable: false
    });

    const mergedText = new fabric.IText("", {
      left: startCol * cellWidth + ((endCol - startCol + 1) * cellWidth) / 2,
      top: startRow * cellHeight + ((endRow - startRow + 1) * cellHeight) / 2,
      fontSize: 12,
      originX: "center",
      originY: "center",
      editable: true,
      selectable: true
    });

    const mergedCellGroup = new fabric.Group([mergedRect, mergedText], {
      left: startCol * cellWidth,
      top: startRow * cellHeight,
      selectable: true,
      hasControls: false,
      hasBorders: false
    });

    tableGroup.addWithUpdate(mergedCellGroup);

    for (let row = startRow; row <= endRow; row++) {
      for (let col = startCol; col <= endCol; col++) {
        const cellIndex = row * (tableGroup.width / cellWidth) + col;
        const cell = cells[cellIndex];
        tableGroup.remove(cell);
      }
    }

    this.canvas.renderAll();
    this.saveState();
  }
}

export default TagGraph;
